package com.siqi.hr.system.custom.dao.mysql;

import com.siqi.hr.common.utils.StringUtil;
import com.siqi.hr.system.common.utils.SelectBoxUtils;
import com.siqi.hr.system.custom.dao.intf.SelectBoxDao;
import com.siqi.hr.system.custom.entity.SelectBox;
import net.sf.json.JSONObject;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 数据字典dao实现类层
 * @author    xiaogq
 * Created by xiaogoingqin on 2016/7/24.
 */
@Component("selectBoxDao")
public class SelectBoxDaoImpl  implements SelectBoxDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Map<String, Object>> getSelectBoxsData(Integer fieldId) {
        String sql = "select * from sys_custom_selectbox where field_id = ?  order by position";
        return jdbcTemplate.queryForList(sql,new Object[] { fieldId });
    }

    @Override
    public int addSelectBox(SelectBox sb) {
        if (sb.isDefaultValue()) {
            String upSql = "update sys_custom_selectbox set default_value = 0 where field_id = ? ";
            jdbcTemplate.update(upSql,new Object[] { sb.getField().getId() });
        }
        //添加枚举字段
        String sql = "insert into sys_custom_selectbox (name,vals_comment,entityId,field_id, default_value) values(?,?,?,?,?)";
        int counts = jdbcTemplate.update(sql,new Object[] {
                sb.getName(),
                sb.getValsComment(),
                sb.getEntityId(),
                sb.getField().getId(),
                sb.isDefaultValue()
        });
        return counts;
    }

    @Override
    public SelectBox getSelectBox(int selectBoxId) {
        String sql = "select * from sys_custom_selectbox where id = ?";
        SelectBox selectBox = jdbcTemplate.queryForObject(sql,new SelectBox.FullSelectBox() , new Object[] {selectBoxId});
        return selectBox;
    }

    @Override
    public int updateSelectBox(SelectBox sb) {
        if (sb.isDefaultValue()) {
            String upSql = "update sys_custom_selectbox  set default_value = 0 where field_id = ? and id <> ?";
            jdbcTemplate.update(upSql,new Object[] {sb.getField().getId(),sb.getId() });
        }
        String sql = "update sys_custom_selectbox set name = ?,vals_comment =?,default_value = ?  where id = ?";
        int counts = jdbcTemplate.update(sql,new Object[] {
            sb.getName(),
            sb.getValsComment(),
            sb.isDefaultValue(),
            sb.getId()
        });
        return counts;
    }

    @Override
    public List<SelectBox> getAllSelectBoxByFieldId(int fieldId,String ids) {
        StringBuffer sql = new StringBuffer("select * from sys_custom_selectbox where field_id = ? ");
        if(StringUtils.isNotBlank(ids)){
            sql.append(" and id in(").append(StringUtil.getString(ids)).append(")");
        }
        sql.append(" order by position ");
        return jdbcTemplate.query(sql.toString(),new Object[] { fieldId },new SelectBox.FullSelectBox());
    }

    @Override
    public int selectBoxSortUpdate(String sortIds) {
        int [] nums = new int [0];
        String [] ids = sortIds.split(",");
        if(ids.length > 0){
            String [] sqls = new String[ids.length];
            for (int i = 0; i < ids.length; i++) {
                String [] strs = ids[i].split("_");
                sqls [i] = "update sys_custom_selectbox set position = "+strs[1]+" where id = "+strs[0];
            }
            if(sqls.length > 0){
                nums = jdbcTemplate.batchUpdate(sqls);
            }
        }
        return nums.length;
    }

    @Override
    public void deleteSelectBox(Integer selectBoxId) {
        String sql = "delete from sys_custom_selectbox where id = ? ";
        jdbcTemplate.update(sql, new Object[] { selectBoxId });
    }

    @Override
    public List<SelectBox> getSelectBoxsNameByIds(String ids) {
        Assert.notNull(ids);
        if(ids.contains(",")){
            ids = ids.substring(1,ids.lastIndexOf(","));
        }
        StringBuffer sql = new StringBuffer("select id,name from sys_custom_selectbox where id in("+ids+") ");
        try {
            return jdbcTemplate.query(sql.toString(), new SelectBox.getSelectBoxNameAndFieldName());
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return new ArrayList<SelectBox>();
    }

    @Override
    public Map<String, Object> extractViewDataValus(Map<String, Object> datasMap,String id) {
        Map<String,Object> resultMap = new LinkedHashMap<String,Object>();
        resultMap.put("id",id);
        for(Map.Entry<String, Object> entry : datasMap.entrySet()){
            String fieldByName = entry.getKey();
            String fieldVal = entry.getValue() == null ? "" : entry.getValue().toString();
            //处理百分比数据
            if(fieldByName.endsWith("_precent") && StringUtils.isNotBlank(fieldVal)){
                resultMap.put(fieldByName, Float.parseFloat( fieldVal.toString() ) * 100 +"%");
            //处理下拉多选类型字段值
            }else if(fieldByName.endsWith("_mutibox") && StringUtils.isNotBlank(fieldVal)){
                List<SelectBox> selBoxs = getSelectBoxsNameByIds(fieldVal);
                resultMap.put(fieldByName, SelectBoxUtils.setNameReplaceId(selBoxs));
            }else {
                resultMap.put(fieldByName, fieldVal);
            }
        }
        return resultMap;
    }

    @Override
    public List<Map<String,Object>> getByEntityId(int entityId) {
        String sql = "select * from sys_custom_selectbox where entityId = '"+entityId+"' ";
        try {
            return jdbcTemplate.queryForList(sql);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
